package com.reebake.ideal.template.util;

import cn.hutool.core.util.ObjectUtil;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.TemplateHashModel;
import lombok.SneakyThrows;

import java.util.Map;

/**
 * freemarker工具
 */
public class TemplateHelper {
    private static BeansWrapper BEANS_WRAPPER_INSTANCE = null;

    public static synchronized BeansWrapper getBeansWrapper() {
        if (ObjectUtil.isNotNull(BEANS_WRAPPER_INSTANCE)) {
            return BEANS_WRAPPER_INSTANCE;
        }
        // Create the builder:
        BeansWrapperBuilder builder = new BeansWrapperBuilder(Configuration.VERSION_2_3_21);
        // Set desired BeansWrapper configuration properties:
        builder.setUseModelCache(true);
        builder.setExposeFields(true);

        // Get the singleton:
        BEANS_WRAPPER_INSTANCE = builder.build();
        return BEANS_WRAPPER_INSTANCE;
    }

    public static void initStaticModels(Map<String, Object> data) {
        data.put("statics", getStaticModels());
    }

    public static TemplateHashModel getStaticModels() {
        return getBeansWrapper().getStaticModels();
    }

    @SneakyThrows
    public static TemplateHashModel getStaticModels(String className) {
        TemplateHashModel staticModels = getStaticModels();
        return (TemplateHashModel) staticModels.get(className);
    }
}
